package com.canplay.screen.service

import android.app.Service
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import android.util.Log
import com.canplay.screen.common.ConstClass.Companion.CHECK_TIME_MESSAGE
import com.canplay.screen.common.ConstClass.Companion.LOG_TAG
import com.canplay.screen.common.ConstClass.Companion.SP_CHECK_TIME
import com.canplay.screen.event.MessageEvent
import com.canplay.screen.init.appContext
import com.canplay.screen.utils.DataHelper
import org.greenrobot.eventbus.EventBus
import java.util.Calendar

class CheckTimeService : Service() {

    private var mHandle: Handler? = null
    private var mRunnable: Runnable? = null
    override fun onBind(intent: Intent?): IBinder? {
        TODO("Not yet implemented")
    }

    override fun onCreate() {
        super.onCreate()
        mHandle = Handler();
        mRunnable = Runnable {
            mRunnable?.let {
                try {
                    Log.d(LOG_TAG, "开始检查时间")
                    checkCurrentTimeNineAM();
                } catch (e: Exception) {
                    Log.e(LOG_TAG, "出错了$e.message")
                } finally {
                    mHandle!!.postDelayed(it, 1000);
                }
            }
        }
    }

    private fun checkCurrentTimeNineAM() {
        val calendar = Calendar.getInstance()
        val year = calendar.get(Calendar.YEAR)
        val month = calendar.get(Calendar.MONTH) + 1 // 月份从0开始，需要加1
        val day = calendar.get(Calendar.DAY_OF_MONTH)
        val data = "$year-$month-$day"

        val hour = calendar.get(Calendar.HOUR_OF_DAY)
        if (hour == 10 || hour == 12 || hour == 15) {
            val timeKey = String.format(SP_CHECK_TIME, data, hour);
            val checkCache: String = DataHelper.getStringSF(appContext, timeKey) ?: "";
            Log.d(LOG_TAG, "timeKey:$timeKey,checkCache$checkCache")
            if (checkCache == "") {
                EventBus.getDefault().post(MessageEvent(CHECK_TIME_MESSAGE, timeKey))
                DataHelper.setStringSF(appContext, timeKey, "checked");
            } else {
                Log.d(LOG_TAG, "这个时间段已经请求了")
            }
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        mRunnable?.let { mHandle?.postDelayed(it, 1000) }
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onDestroy() {
        mRunnable?.let { mHandle?.removeCallbacks(it) }
        super.onDestroy()
    }
}